package com.zy.ems.common.util;

import java.util.Locale;

import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.stereotype.Component;

/**
 * 消息处理工具类。
 * 
 * @author Luffy
 * 
 */
@Component
public final class MessageUtils implements MessageSourceAware {

    /**
     * 提供获取消息的简便方法
     */
    private static MessageSourceAccessor messageSourceAccessor;

    /**
     * 获取指定编码的消息内容，未找到对应消息时返回空字符串。
     * 
     * @param code
     * @return
     */
    public static String getMessage(String code) {
        return messageSourceAccessor.getMessage(code, StringUtils.EMPTY);
    }

    /**
     * 获取指定编码的消息内容，未找到对应消息时返回指定的默认消息。
     * 
     * @param code
     * @param defaultMessage
     * @return
     */
    public static String getMessage(String code, String defaultMessage) {
        return messageSourceAccessor.getMessage(code, defaultMessage);
    }

    /**
     * 获取指定编码的消息内容，未找到对应消息时返回空字符串。
     * 
     * @param code
     * @param args
     * @return
     */
    public static String getMessage(String code, Object[] args) {
        return messageSourceAccessor.getMessage(code, args, StringUtils.EMPTY);
    }

    /**
     * 获取指定编码的消息内容，未找到对应消息时返回指定的默认消息。
     * 
     * @param code
     * @param args
     * @param defaultMessage
     * @return
     */
    public static String getMessage(String code, Object[] args,
            String defaultMessage) {
        return messageSourceAccessor.getMessage(code, args, defaultMessage);
    }

    /**
     * Try to resolve the message. Return default message if no message was
     * found.
     * 
     * @param code
     *            the code to lookup up.
     * @param args
     *            array of arguments that will be filled in for params within
     *            the message (params look like "{0}", "{1,date}", "{2,time}"
     *            within a message), or {@code null} if none.
     * @param defaultMessage
     *            String to return if the lookup fails
     * @param locale
     *            the Locale in which to do the lookup
     * @return the resolved message if the lookup was successful; otherwise the
     *         default message passed as a parameter
     */
    public static String getMessage(String code, Object[] args,
            String defaultMessage, Locale locale) {
        return messageSourceAccessor.getMessage(code, args, defaultMessage,
                locale);
    }

    public void setMessageSource(MessageSource messageSource) {
        if (messageSource == null) {
            throw new IllegalStateException(
                    "'messageSource' property is null.");
        }
        if (messageSourceAccessor != null) {
            throw new IllegalStateException(
                    "MessageUtils already holded 'messageSource'.");
        }
        messageSourceAccessor = new MessageSourceAccessor(messageSource);
    }

}
